
# data uitls
pacman::p_load(data.table, tidyverse, rio, boot, magrittr)
#  panel / factor model packages
pacman::p_load(synthdid, kernlab, ebal, grf, npcausal, estimatr)
set.seed(42)
if (Sys.info()[['user']] == "alal") {
  root = "/home/alal/Dropbox/1_Research/ElecAdminFunding/ElecAdminFundingReplication"
} else {
  root = "~/Dropbox/ElecAdminFunding/ElecAdminFundingReplication"
}

# Prepare the Wisconsin analysis file
wi_raw = rio::import(file.path(root, "/modified_data/wi_analysis_file.dta")) %>% setDT
wi_raw[, treated := ifelse(treat==1 & year == 2020, 1, 0)]
wi_no_funded_counties = wi_raw[in_funded_county==0,]

# Get synth diff-in-diff estimates of CTCL grant on
# dem vote share in Wisconsin municipalities
wi_allsynth_dem = panel_estimate(wi_raw,
    "place", "year", "treated", "vs_dem", 
    methods=c("DID", "Time Weighted DID", 
      "DIFP (Regularized)", "Synthetic DID (SDID)"),
    mccores = 14, reps = 1000,
  infmethod = "bootstrap")

# Get synth diff-in-diff estimates of CTCL grant on
# turnout in Wisconsin municipalities
wi_allsynth_tur = panel_estimate(wi_raw,
    "place", "year", "treated", "turnout_pres", 
    methods=c("DID", "Time Weighted DID", 
      "DIFP (Regularized)", "Synthetic DID (SDID)"),
    mccores = 15, reps = 1000,
  infmethod = "bootstrap")

# Get synth diff-in-diff estimates of CTCL grant on
# dem vote share in Wisconsin municipalities not in
# counties that received a grant
wi_no_funded_counties_allsynth_dem = panel_estimate(wi_no_funded_counties,
    "place", "year", "treated", "vs_dem", mccores = 14, reps = 1000,
  infmethod = "bootstrap")

# Get synth diff-in-diff estimates of CTCL grant on
# turnout in Wisconsin municipalities not in counties 
# that received a grant
wi_no_funded_counties_allsynth_tur = panel_estimate(wi_no_funded_counties,
    "place", "year", "treated", "turnout_pres", mccores = 15, reps = 1000,
  infmethod = "bootstrap")

# Save the combined output
save(wi_allsynth_dem, wi_allsynth_tur, 
    wi_no_funded_counties_allsynth_dem,
    wi_no_funded_counties_allsynth_tur,
    file = file.path(root, "tmp/wi_allsynth.RData"))

